package com.example.administrator.szb.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.example.administrator.szb.R;
import com.example.administrator.szb.adapter.BaseAdapter;
import com.example.administrator.szb.adapter.MyOnScroll;
import com.example.administrator.szb.activity.base.BaseActivity;
import com.example.administrator.szb.bean.GZBean;
import com.example.administrator.szb.bean.MyGZBean;
import com.example.administrator.szb.bean.RzBean;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.HttpUtils;
import com.example.administrator.szb.http.OnResultListener;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.DialogUtil;
import com.example.administrator.szb.util.GetJsonDataUtil;
import com.example.administrator.szb.util.Toasts;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by D N on 2017/9/27.
 * 我的关注
 */

public class MyGZActivity extends BaseActivity {
    @Bind(R.id.mygz_image_fh)
    ImageView mygzImageFh;
    @Bind(R.id.mygz_recyclerview)
    RecyclerView mygzRecyclerview;
    private int current_page = 1;
    private int per_page = 10;

    MyGZBean mYGZBean;
    ArrayList<MyGZBean.DataBean> mdata;
    private BaseAdapter<MyGZBean.DataBean> adapter;
    private View footerview;
    private boolean isDataChange = false;
    View error_head;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_gz_activity);
        ButterKnife.bind(this);
        SampleApplicationLike.getActivitiesInstance().add(this);
        footerview = LayoutInflater.from(this).inflate(R.layout.view_wd_footer, null);
        footerview.setVisibility(View.INVISIBLE);
        mdata = new ArrayList<>();
        requestGZ();
    }

    private void requestGZ() {
        HashMap<String,Object> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("id", SampleApplicationLike.getUserloginInstance().getId()+"");
        map.put("current_page",current_page+"");
        map.put("per_page",per_page+"");
        String json = GetJsonDataUtil.simpleMapToJsonStr(map);
        String url = URLAddress.URLBASE + URLAddress.URL_MYGZ;
        HttpUtils.post2(activity,url, map, 0, new OnResultListener() {
            @Override
            public void onSuccess(int requestCode, String str) {
                try {
                    mYGZBean = JSON.parseObject(str,new TypeReference<MyGZBean>(){});


                } catch (Exception e) {
                    str = str.replace("\"data\":{}","\"data\":[]");
                    mYGZBean = JSON.parseObject(str,new TypeReference<MyGZBean>(){});
                    e.printStackTrace();
                }
                if (mYGZBean.getData()==null){
                    mYGZBean.setData(new ArrayList<MyGZBean.DataBean>());
                }
                if (mYGZBean.getResult() == 1 && current_page == 1){
                    mdata.addAll(mYGZBean.getData());
                    initView();
                    current_page = current_page +1;
                }else if(mYGZBean.getResult() == 1){
                    current_page = current_page +1;
                    mdata.addAll(mYGZBean.getData());
                    adapter.notifyDataSetChanged();
                    footerview.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onFailure(int requestCode, String str) {
                footerview.setVisibility(View.INVISIBLE);
                // Toasts.show(MyGZActivity.this, "没有数据了", Toast.LENGTH_SHORT);
                DialogUtil.showToast(MyGZActivity.this,"发生异常，再试一次吧");
            }
        });
    }

    private void initView() {
        mygzRecyclerview.setLayoutManager(new LinearLayoutManager(this));
        initAdapter();

        if (mdata.size() == 0 ){
            error_head = LayoutInflater.from(MyGZActivity.this).inflate(R.layout.view_item_error,mygzRecyclerview,false);
            ((TextView)error_head.findViewById(R.id.text_view_error)).setText("您还没有关注别人哦");
            adapter.addHeaderView(error_head);
        }else{
            adapter.addFootView(footerview);
            loadMore();//开启加载更多监听
        }
        mygzRecyclerview.setAdapter(adapter);

    }
    /**
     * 开启加载更多
     */
    private void loadMore() {

        mygzRecyclerview.addOnScrollListener(new MyOnScroll(){
            @Override
            public void scrollBottom() {
                    super.scrollBottom();
                    footerview.setVisibility(View.VISIBLE);
                    requestGZ();
            }
        });
    }

    private void initAdapter() {
        adapter = new BaseAdapter<MyGZBean.DataBean>(this,mdata) {
            @Override
            public void convert(int position, BaseViewHolder holder, MyGZBean.DataBean dataBean) {
                    initItem(holder,dataBean);//填充数据
            }

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.view_mygz_item;
            }
        };

        adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent_go = new Intent(MyGZActivity.this, GWCententActivity.class);
                intent_go.putExtra("refer_id", mdata.get(position).getId());
                startActivity(intent_go);
            }
        });
    }

    private void initItem(final BaseAdapter<MyGZBean.DataBean>.BaseViewHolder holder, final MyGZBean.DataBean dataBean) {
        ((TextView)holder.getView(R.id.textView54)).setText(dataBean.getName());
        if (dataBean.getReal_name()!=null&&dataBean.getReal_name().size()>0&&dataBean.getReal_name().get(0).length()>0){
            //String arr[] = dataBean.getReal_name().split("-");
            ((TextView)holder.getView(R.id.textView54)).setText(dataBean.getName()+"("+dataBean.getReal_name().get(0)+"经理)");
        }
        if (!TextUtils.isEmpty(dataBean.getHeadimg())) {
            Glide.with(MyGZActivity.this).load(dataBean.getHeadimg()).error(R.drawable.mrtx).into((ImageView) holder.getView(R.id.imageView26));
        }

        ((CheckBox)holder.getView(R.id.checkBox2)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    ((CheckBox)holder.getView(R.id.checkBox2)).setText("关注");
                    ((CheckBox)holder.getView(R.id.checkBox2)).setTextColor(getResources().getColor(R.color.basecolor2));
                    ((CheckBox)holder.getView(R.id.checkBox2)).setBackground(getResources().getDrawable(R.drawable.border_content2));
                    requestCancleGZ(dataBean.getId());
                }else{
                    ((CheckBox)holder.getView(R.id.checkBox2)).setText("取消关注");
                    ((CheckBox)holder.getView(R.id.checkBox2)).setTextColor(getResources().getColor(R.color.gray1));
                    ((CheckBox)holder.getView(R.id.checkBox2)).setBackground(getResources().getDrawable(R.drawable.border_content3));
                    requestGZAgain(dataBean.getId());
                }
            }
        });

        if (dataBean.getType() == 2){
            ((TextView)holder.getView(R.id.textView67)).setVisibility(View.VISIBLE);
        }
    }

    /**
     * 关注
     * @param id
     */
    private void requestGZAgain(int id) {
        HashMap<String,String> map = new HashMap<>();
        map.put("code",HttpUtil.getParam());
        //int id = SampleApplicationLike.getUserloginInstance().getId();
        map.put("id",SampleApplicationLike.getUserloginInstance().getId()+"");
        map.put("quiz_id",id+"");
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, GZBean.class, URLAddress.URLBASE + URLAddress.URL_GZ, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                GZBean gzBean = (GZBean) response;
                if (gzBean.getResult() == 1){
                    DialogUtil.showSimpleDialog(MyGZActivity.this,gzBean.getData().getMsg());
                }else{
                    DialogUtil.showSimpleDialog(MyGZActivity.this,gzBean.getErr_msg());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.toString();
                DialogUtil.showSimpleDialog(MyGZActivity.this,"服务器异常，请重新尝试");
            }
        });
    }

    /**
     * 取消关注
     * @param id
     */
    private void requestCancleGZ(int id) {
        HashMap<String,String> map = new HashMap<>();
        map.put("code",HttpUtil.getParam());
        map.put("id",SampleApplicationLike.getUserloginInstance().getId()+"");
        map.put("quiz_id",id+"");
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, RzBean.class, URLAddress.URLBASE + URLAddress.URL_CANCLE_ALL_GZ, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                RzBean rZBean = (RzBean) response;
                if (rZBean.getResult() == 1) {
                    isDataChange = true;
                    DialogUtil.showSimpleDialog(MyGZActivity.this, "取消成功");
                }else{
                    Toasts.show(MyGZActivity.this, ""+rZBean.getErr_msg(), Toast.LENGTH_SHORT);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toasts.show(MyGZActivity.this, ""+error.toString(), Toast.LENGTH_SHORT);
            }
        });
    }

    @OnClick(R.id.mygz_image_fh)
    public void onViewClicked() {
        finish();
    }

    @Override
    public void onBackPressed() {
        if (isDataChange) {
           // HomeActivity.isLogin_or_register = true;
        }

        super.onBackPressed();
    }
}
